#include <iostream>
#include <string>
#include <memory>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

void Usage(const char *proc)

{
    std::cout << proc << ",svrip:svrport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    int svrport = std::stoi(argv[2]);
    std::string ip = argv[1];

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "创建套接字失败" << std::endl;
        exit(-1);
    }

    // 填充server的信息
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(svrport);
    inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if(n<0){
        std::cout<<"连接服务器失败"<<std::endl;
        exit(-2);
    }
    //std::cout << "连接服务器的结果:" << n << std::endl;
    while (true)
    {
        // 可以通信了
        std::string buffer;
        std::cout << "please Enter#";
        std::getline(std::cin, buffer);
        int m = write(sockfd, buffer.c_str(), buffer.size());
        char message[1024];
        if (m > 0)
        {
            n = read(sockfd, message, sizeof(message) - 1);
            if (n > 0)
            {
                std::cout << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }

    close(sockfd);
    return 0;
}